<template>
  <div class="verification-code">
    <el-input
      ref="codeRef"
      v-model.trim="code"
      :maxlength="props.maxlength"
      :placeholder="props.placeholder"
      class="verification-code--input"
      type="text"
      autocomplete="off"
      size="large"
      @input="inputHandle"
    />
    <el-button
      :loading="loading"
      :disabled="isCountdown"
      class="verification-code--button"
      @click="sendCodeHandle"
    >
      <span v-if="!isCountdown">获取验证码</span>
      <span v-else>{{ time }}秒</span>
    </el-button>
  </div>
</template>

<script setup>
// apis
import { captcha } from '@/api/common'
// others
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

const props = defineProps({
  mobile: { type: [Number, String], default: '' },
  value: { type: [Number, String], default: '' },
  maxlength: { type: Number, default: 6 },
  placeholder: { type: String, default: '请输入验证码' }
})
const emit = defineEmits(['validate', 'input'])

const loading = ref(false)
const code = ref(props.value)
const time = ref(60)
const timer = ref(null)
const isCountdown = ref(false)

const inputHandle = (val) => {
  // code.value = val.replace(/[^\d]/g, '')
  emit('input', code.value)
}
// 倒计时
const countdown = () => {
  if (time.value === 0) {
    clearTimeout(timer.value)
    time.value = 60
    isCountdown.value = false
    return
  } else {
    isCountdown.value = true
    time.value--
  }
  timer.value = setTimeout(() => {
    countdown()
  }, 1000)
}
// 接口
const sendCodeHandle = async () => {
  if (!props.mobile) {
    emit('validate')
    return
  }
  loading.value = true
  try {
    const res = await captcha({ mobile: props.mobile, captchaType: 'LOGIN' })
    console.log('res', res)
    if (res.errno === 0) {
      isCountdown.value = true
      countdown()
      ElMessage.success('发送成功')
    }
  } catch (res) {
    console.log(res)
  }
  loading.value = false
}
</script>

<style lang="less" scoped>
.verification-code {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  &--button {
    width: 130px;
    height: 40px;
    margin-left: 12px;
  }
}
</style>
